"""
@author: yinjx
@file: loneusercomment.py
@time: 2023/8/12 15:52
"""


from . import lonecomment_bp
from flask_restful import Api, Resource
from router.keysearchbook.addcomment import token_reauth
from models.user import User, Book, Category, Comment
from flask import request, current_app
from libs.response import generate_response
from models import db

api = Api(lonecomment_bp)

class LoneComments(Resource):
    @token_reauth
    def get(self):
        # book = Book.query.get(book_id)
        my_user = request.args.get('my_user')
        print(my_user)
        user = User.query.filter_by(username=my_user).first()
        comments = Comment.query.filter_by(user_id=user.id).all()

        result = []
        for comment in comments:
            book = Book.query.get(comment.book_id)
            result.append({
                'comment': comment.content,
                'comment_id': comment.id,
                'title': book.title,
                'book_id': book.id,
                'user_avatar': user.avatar

            })
        print(result)
        return generate_response(message="get success!", data=result)
    def delete(self):
        comment_id = request.args.get('comment_id')

        comment = Comment.query.get(comment_id)

        if comment:
            # 找到了对应的评论，进行删除
            db.session.delete(comment)
            db.session.commit()
            return generate_response(code=0, message="delete success!")
        else:
            return generate_response(code=1, message="comment not found!")

        # book_id = request.json.get('book_id')
        # my_user = request.json.get('my_user')
        # comment_id = request.json.get('comment_id')
        #
        # book = Book.query.filter_by(book_id=book_id).all()
        # comments = Comment.query.filter_by(comment_id=comment_id).all()
        # user = User.query.filter_by(username=my_user).first()

api.add_resource(LoneComments, "/user", endpoint="lonebook_comments")
